import React, { Component } from 'react';
import { Form, Input, Button, Icon, Checkbox, Drawer, message } from 'antd';
import handleStorage from '../../utils/handleStorage';
import { connect } from 'dva';
import styles from './style/index.less';
import DragModal from '../components/DragModal';
// @connect(
//   (state) => ({state.login })
// )
@connect((state) =>
({
  userInfo: state.layout.userInfo
})
)
class Login extends Component {

  // 输入框布局样式
  layout = {
    wrapperCol: {
      span: 16,
      offset: 4,
    },
  };
  // 登录按钮布局样式
  tailLayout = {
    wrapperCol: {
      offset: 4,
    },
  };

  // 弹出框表单样式
  formItemLayout = {
    labelCol: {
      span: 8,
      offset: 0,
    },
    wrapperCol: {
      span: 14,
      offset: 0,
    },
  };

  state = {
    validateFlag: 0,
    visible: false,
    drawerVisible: false,
    uid: ''
  }

  // 登录请求
  login = (values) => {
    this.props.dispatch({
      type: 'gislogin/login',
      payload: { ...values },
      callback: (flag, data) => {
        this.setState({
          validateFlag: flag ? 0 : 1
        }, () => {
          if (flag) {
            // 清除之前的token 将新的token保存
            handleStorage.removeStorage('gis-token');
            handleStorage.removeStorage('gis-user');
            handleStorage.setStorage('gis-token', data.token);
            // 保存用户信息
            handleStorage.setStorage('gis-user', data.uid);
            // 如果登录成功 跳转到 首页
            this.props.history.push('/');
          }
        });
      }
    })
  }

  // 忘记密码
  forgetPsd = e => {
    e.preventDefault();
    // DragModal
    this.setState({
      visible: true
    });
  }

  // 重置密码按钮事件
  findPsd = e => {
    e.preventDefault();
    this.props.form.validateFields(['_username', '_phone'], (err, values) => {
      if (err) return false;
      // 发送请求判断当前输入的账号和手机号是否匹配
      this.props.dispatch({
        type: 'gislogin/checkUser',
        payload: {
          ...values
        }
      }).then(res => {
        if (!res) {
          message.error('用户名或手机号码错误！');
          return false;
        }
        this.setState({
          uid: res
        }, () => {
          // 重置抽屉
          this.resetDrawer = false;
          this.showDrawer();
        })
      })
    });
  };

  // 显示重置密码抽屉
  showDrawer = () => {
    this.setState({
      drawerVisible: true,
    });
  };

  // 关闭重置密码抽屉
  handleClose = () => {
    this.setState({
      drawerVisible: false,
    });
  }

  // 重置密码
  resetPsd = (e) => {
    e.preventDefault();
    const { uid } = this.state;
    this.props.form.validateFields(['newpassword', 'confpassword'], (err, values) => {
      if (err) return false;
      this.props.dispatch({
        type: 'gislogin/resetPassword',
        payload: {
          uid,
          password: values.newpassword
        }
      }).then(res => {
        if (res) {
          const { msg } = res;
          message.success(msg);
          this.setState({
            uid: '',
            visible: false,
            drawerVisible: false
          })
          return;
        }
        message.error('修改失败，服务器异常请稍后重试');
      })
    });
  }

  // 表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields(['username', 'password'], (err, values) => {
      if (err) return false;
      this.login(values);
    });
  };



  render() {
    const { getFieldDecorator } = this.props.form;
    const modalOption = {
      title: "找回密码",
      size: 'small',
      callback: () => { this.resetDrawer = true }
    }
    return (
      <div className={styles.layout}>
        <div className={styles.loginForm}>
          <div className={styles.title}>
            用户登录
          </div>
          {/* <div className={styles.img}>
            <span>石门水务综管系统</span>
          </div> */}
          <div className={styles.ruleMessage} style={{ opacity: this.state.validateFlag }}>
            <Icon type="warning" style={{ color: 'red' }} /> <span>账号或密码错误，请重新输入!</span>
          </div>
          <div>
            <Form
              {...this.layout}
              name="loginForm"
              style={{ marginTop: '5px' }}
            >
              <Form.Item>
                {getFieldDecorator('username', {
                  rules: [{ required: true, message: '请输入用户名!', whitespace: true }],
                })(
                  <Input
                    prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    placeholder="用户名：请输入用户名"
                  />,
                )}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '请输入密码!', whitespace: true }],
                })(
                  <Input
                    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    placeholder="密码：请输入密码"
                    type='password'
                  />,
                )}
              </Form.Item>
              <Form.Item style={{ marginBottom: '0px' }}>
                {getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: true,
                })(<Checkbox>记住我</Checkbox>)}
                <a className={styles.forgetPsd} href="#!" onClick={this.forgetPsd}>忘记密码? </a>
              </Form.Item>
              <Form.Item {...this.tailLayout}>
                <Button onClick={this.handleSubmit} style={{ width: 226, height: 36, borderRadius: 4 }} type="primary" htmlType="submit">
                  登 录
              </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className={styles.findPsdForm} >
          <DragModal visible={this.state.visible} {...modalOption}>
            <div style={{ position: 'relative', overflow: 'hidden', }}>
              <Form name='findPsdForm' {...this.formItemLayout}>
                <Form.Item label="用户名">
                  {getFieldDecorator('_username', {
                    rules: [{ required: true, message: '用户名不能为空!' }],
                  })(
                    <Input />,
                  )}
                </Form.Item>
                <Form.Item label="手机号码">
                  {getFieldDecorator('_phone', {
                    rules: [{ required: true, message: '手机号码不能为空!' },],
                  })(
                    <Input />,
                  )}
                </Form.Item>
                <Form.Item label="电子邮箱(选填)">
                  {getFieldDecorator('_email', {})(
                    < Input />,
                  )}
                </Form.Item>
                <Form.Item
                  wrapperCol={{
                    span: 24, offset: 17,
                  }}
                >
                  <Button type="primary" htmlType="submit" onClick={this.findPsd}>
                    重置密码
                </Button>
                </Form.Item>
              </Form>
              {/* 重置密码 */}
              <Drawer
                title="重置密码"
                placement="right"
                closable={false}
                width={300}
                onClose={this.handleClose}
                visible={this.resetDrawer ? false : this.state.drawerVisible}
                getContainer={false}
                style={{ position: 'absolute' }}
                destroyOnClose={true}
              >
                <Form name='findPsdForm' {...this.formItemLayout}>
                  <Form.Item label="新密码">
                    {getFieldDecorator('newpassword', {
                      rules: [{ required: true, message: '新密码不能为空!' }],
                    })(
                      <Input type='password' />,
                    )}
                  </Form.Item>
                  <Form.Item label="确认密码">
                    {getFieldDecorator('confpassword', {
                      rules: [{ required: true, message: '确认密码不能为空!' },
                      {
                        validator: (rule, value, callback) => {
                          const newPwd = this.props.form.getFieldValue('newpassword');
                          if (value && value !== newPwd) {
                            callback('两次密码输入不一致!');
                          }
                          callback();
                        }
                      }],
                    })(
                      <Input type='password' />,
                    )}
                  </Form.Item>
                  <Form.Item
                    wrapperCol={{
                      span: 24, offset: 10,
                    }}
                  >
                    <Button type="primary" htmlType="submit" onClick={this.resetPsd}>
                      确认
                </Button>
                  </Form.Item>
                </Form>
              </Drawer>
            </div>
          </DragModal>
        </div>
      </div >
    );
  }
}
const WrappedNormalLoginForm = Form.create({ name: 'login' })(Login);
export default WrappedNormalLoginForm;
